<?php

namespace App\Models;

use D1M\Payment\Models\ShouQianBa\Payment as SqbPayment;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Refund extends Model
{
    use HasFactory;


    public static $statusMap = [
        0=>'退款中',
        1=>'退款成功',
        2=>'退款失败',
        3=>'部分退款成功',
    ];

    public static function modifierStatus($key)
    {
        return [
            'title'=>self::$statusMap[$key]??'',
            'code'=>$key,
        ];
    }

    public function refundDetail(){
        return $this->hasMany(RefundDetail::class,'refunds_id');
    }

    public function updateRefundStatus($id){
        $refund = self::query()->with('refundDetail')->find($id);
        if($refund->status===1){
            return $refund;
        }

        $succ = 0;
        foreach ($refund->refundDetail as $detail){
            if($detail->status===1){
                $succ += 1;
            }
        }
        if($succ){
            $detailCount = $refund->refundDetail->count();
            if($succ==$detailCount){
                $refund->status = 1;//全部成功
            }else{
                $refund->status = 3;//部分成功
            }
        }else{
            $refund->status = 2;
        }

        $refund->save();

        return $refund;
    }

    public function getPayment($order_no){
        $payInfos = DB::select("SELECT p.id,p.payment_method ,p.amount,p.operator FROM combined_payment c left join payment p on c.id =p.combined_payment_id  WHERE c.business_order_no = ? and c.business_scene ='placing_order' and c.status ='paid' and p.status = 'paid'", [$order_no]);
        $refundInfo = RefundDetail::where('order_no',$order_no)->where('status',1)->get(['refund_platform','refund_amount','tenders'])->toArray();
        $refundList = $shouqianbaRefund = [];
        if($refundInfo){
            foreach ($refundInfo as $item){
                if(!isset($refundList[$item['refund_platform']])){
                    $refundList[$item['refund_platform']] = 0;
                }
                $refundList[$item['refund_platform']] += $item['refund_amount'];
                if(in_array($item['refund_platform'], ['shouqianba','ali_pay','wx_pay','bank_card']) && $item['tenders']){
                    $tenders = json_decode($item['tenders'],true);
                    foreach ($tenders as $tender){
                        if(!isset($shouqianbaRefund[$tender['original_tender_sn']])){
                            $shouqianbaRefund[$tender['original_tender_sn']] = 0;
                        }
                        $shouqianbaRefund[$tender['original_tender_sn']] += abs($tender['amount']);
                    }
                }
            }
        }
        Log::info('已退款：'.var_export($refundList,1));
        Log::info('已退款(收钱吧)：'.var_export($shouqianbaRefund,1));
        Log::info('订单支付详情：'.var_export($payInfos,1));
        $payItem = [];
        foreach ($payInfos as $pay) {
            $items = [];
            if(isset($refundList[$pay->payment_method])){
                //支付方式全部退款
                if($refundList[$pay->payment_method]>=$pay->amount){
                    continue;
                }else{
                    $pay->amount -= $refundList[$pay->payment_method];
                }
            }
            $items['pay_platform'] = $pay->payment_method;
            $items['pay_amount'] = $pay->amount;
            $items['operator'] = $pay->operator;
            if (in_array($items['pay_platform'], ['shouqianba','ali_pay','wx_pay','bank_card'])) {
                $sqbPayment = SqbPayment::where('payment_id', $pay->id)->first();
                $items['store_sn'] = $sqbPayment->store_sn;

                foreach ($sqbPayment->tenders as $tender){
                    if(isset($shouqianbaRefund[$tender->tender_sn])){
                        if($shouqianbaRefund[$tender->tender_sn]>=$tender->amount){
                            continue;
                        }else{
                            $tender->amount -= $shouqianbaRefund[$tender->tender_sn];
                        }
                    }
                    $items['tenders'][] = [
                        'id'=>$tender->id,
                        'tender_sn'=>$tender->tender_sn,
                        'amount'=>$tender->amount,
                    ];
                }
            }

            $payItem[] = $items;
        }
        Log::info('可退款明细：'.var_export($payItem,1));
        return $payItem;
    }
}
